package com.myjob.controller;

import com.myjob.entity.Comment;
import com.myjob.exception.OptionException;
import com.myjob.response.Result;
import com.myjob.service.CommentService;
import com.myjob.utils.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Chen Yuan
 * @create 2021-01-21  19:10
 */
@RestController
@Slf4j
@RequestMapping("/blog")
public class CommentController {
	@Autowired
	private CommentService commentService;

	@GetMapping("/commentInfo")
	public Result selectComments(@RequestParam("blogId") String blogId){
		Result result = null;
		try {
			List<List<Comment>> comments = commentService.selectComments(blogId);
			result = Result.succeed(comments);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@GetMapping("/selectCommentByUser")
	public Result selectCommentByUser(@RequestParam(value = "userId")String userId,
									  @RequestParam(value = "searchValue", required = false)String searchValue,
									  @RequestParam(value = "currentPage")Integer currentPage,
									  @RequestParam(value = "pageSize", required = false)Integer pageSize){
		Result result = null;
		try {
			if (UtilValidate.isEmpty(userId)) {
				return Result.failed("参数为空");
			}
			result = commentService.selectCommentsByUser(userId, searchValue,
					currentPage, pageSize);
		}catch (Exception e){
		    e.printStackTrace();
		    throw new OptionException("查询博客对应的评论出错");
		}
		return result;
	}


	@PostMapping("/commentInfo")
	public Result addComment(@RequestBody Comment comment){
		Result result = null;
		try {
			// 添加默认值
			comment.setDeleted(0);
			int insert = commentService.addComment(comment);
			if (insert == 1){
				result = Result.succeed("评论成功");
			}else {
				result = Result.failed("评论出错");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


	@DeleteMapping("/commentInfo")
	public Result deleteComment(@RequestParam("commentId") String commentId){
		Result result = null;
		try {
			int delete = commentService.deleteComment(commentId);
			if (delete == 1){
				result = Result.succeed("评论 删除成功");
			}else {
				result = Result.failed("评论 删除失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
